/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import models.ActionsTableModel;
import utils.ChocoDate;
import utils.ChocoFileAccess;

/**
 * The class that contains the 12 months of a year.
 * @author chocoseb
 */
public class Year {

    private int _yearNumber = 1995;
    private double _account;
    private Month[] _months = new Month[12];
    private int _selectedMonth = 0;
    private ArrayList<JComboBox> _listMonthCombo = new ArrayList<JComboBox>();
    private ActionsTableModel _model = new ActionsTableModel();
    private JLabel _lblIncomes;
    private JLabel _lblExpenses;
    private JLabel _lblDeficit;
    private JLabel _lblRemain;

    /**
     * Create a new year and initialise the months array.
     */
    public Year(int p_year) {
        _yearNumber = p_year;
        ChocoFileAccess.createDirIfNotExist(this.getFolderName());
        for (int i = 0; i < 12; i++) {
            _months[i] = new Month(this, i);
        }
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(this.getFileName()));
            _account = in.readDouble();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Year(int p_year, double p_account){
        _yearNumber = p_year;
        ChocoFileAccess.createDirIfNotExist(this.getFolderName());
        for (int i = 0; i < 12; i++) {
            _months[i] = new Month(this, i);
        }
        _account = p_account;
    }

    /**
     * Return the path for the folder in wich the file reprenting the year will be stored.
     * @return
     */
    public String getFolderName() {
        return String.valueOf(_yearNumber);
        //return String.valueOf(_yearNumber) + "_" + String.valueOf(_yearNumber + 1);
    }

    /**
     * Get the path and filename for the file that will contains this month actions.
     * @return
     */
    public String getFileName() {
        return this.getFolderName() + "\\year.bdj";
    }

    /**
     * Save all the month in their respecting file
     */
    public void save() {
        for (int i = 0; i < 12; i++) {
            _months[i].save();
        }
        try {
            DataOutputStream out = new DataOutputStream(new FileOutputStream(this.getFileName()));
            out.writeDouble(_account);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Bind a JTable with the actions of the currently selected month.
     * @param paTable
     */
    public void addActionsTable(JTable paTable){
        paTable.setModel(_model);
        _model.updateWithMonth(_months[_selectedMonth]);
    }

    /**
     * Bind a JComboBox with the list of the months
     * @param p_combo
     */
    public void addMonthSelectionComboBox(JComboBox p_combo) {
        p_combo.removeAllItems();
        for (int i = 0; i < 12; i++) {
            p_combo.addItem(_months[i].getMonthName());
        }
        p_combo.setSelectedIndex(_selectedMonth);
        p_combo.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                _selectedMonth = ((JComboBox) e.getSource()).getSelectedIndex();
                monthChanged();
            }
        });
        _listMonthCombo.add(p_combo);
    }

    /**
     * Bind a bouton with the action of going to the next month
     * @param btn
     */
    public void addNextButton(JButton btn) {
        btn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (_selectedMonth < 11) {
                    _selectedMonth++;
                    monthChanged();
                }
            }
        });

    }

    /**
     * Bind a bouton with the action of going to the previous month
     * @param btn
     */
    public void addPreviousButton(JButton btn) {
        btn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (_selectedMonth > 0) {
                    _selectedMonth--;
                    monthChanged();
                }
            }
        });

    }

    public void bindIncomeLabel(JLabel lbl){
        _lblIncomes = lbl;
    }

    public void bindExpenseLabel(JLabel lbl){
        _lblExpenses = lbl;
    }

    public void bindDeficit(JLabel lbl){
        _lblDeficit = lbl;
    }

    public void bindRemain(JLabel lbl){
        _lblRemain = lbl;
    }

    /**
     *
     * @return The selected index
     */
    public int getSelectedMonth() {
        return _selectedMonth;
    }

    /**
     *
     * @return The selected Month object
     */
    public Month getSelectedMonthRef(){
        return _months[_selectedMonth];
    }

    /**
     * The month object corresponding to the month number.
     * @param index From 0 to 11
     * @return
     */
    public Month getMonthRef(int index){
        return _months[index];
    }

    /**
     * Method called when the month is changed.
     */
    private void monthChanged() {
        for (JComboBox c : _listMonthCombo) {
            c.setSelectedIndex(_selectedMonth);
            _model.updateWithMonth(_months[_selectedMonth]);
            calculateStatistic();
        }
    }

    public void calculateStatistic(){
        if (_lblIncomes != null){
            _lblIncomes.setText(String.valueOf(getSelectedMonthRef().getMonthIncomes()));
        }
        if (_lblExpenses != null){
            _lblExpenses.setText("(" + String.valueOf(getSelectedMonthRef().getMonthExpense()) + ")");
        }
        if (_lblDeficit != null){
            double deficit = getSelectedMonthRef().getMonthDeficit();
            String s = String.valueOf(deficit);
            if (deficit < 0){
                s = "(" + s + ")";
                _lblDeficit.setForeground(Color.red);
            }else{
                _lblDeficit.setForeground(Color.blue);
            }
            _lblDeficit.setText(s);
        }
        if (_lblRemain != null){
            double remain = calculateRemain();
            String s = String.valueOf(remain);
            if (remain < 0){
                s = "(" + s + ")";
                _lblRemain.setForeground(Color.red);
            }else{
                _lblRemain.setForeground(Color.blue);
            }
            _lblRemain.setText(s);
        }
    }

    private double calculateRemain(){
        double remain = _account;
        for (int i = 0; i <= _selectedMonth; i++){
            remain += _months[i].getMonthDeficit();
        }
        return remain;
    }

    /**
     * Delete the selected action of a JTable
     * @param table The table that contains the actions.
     */
    public void deleteSelectedIndex(JTable table){
        int index = table.getSelectedRow();
        if (index >= 0){
            _months[_selectedMonth].deleteAtIndex(index);
            _model.fireTableDataChanged();
        }
    }

    /**
     * Get the current Year Number (First number of 2011-2012) for a year that start
     * the 1st of July.
     * @return (INT) The current year
     */
    public static int currentYear() {
        Calendar now = ChocoDate.now();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH);
        return year;
//        if (month >= 6) {
//            return year;
//        }
//        return year - 1;
    }
}
